# food_app/forms.py
from django import forms
from .models import Tag, FoodItem, DailyFoodRecord, Recipe, RecipeIngredient, RecipeStep


class TagForm(forms.ModelForm):
    class Meta:
        model = Tag
        fields = ['name', 'color', 'description', 'parent']
        widgets = {
            'color': forms.TextInput(attrs={'type': 'color'}),
            'description': forms.Textarea(attrs={'rows': 3}),
            'parent': forms.Select(attrs={'class': 'form-select'}),
        }
        labels = {
            'name': '标签名称',
            'color': '标签颜色',
            'description': '标签描述',
            'parent': '父级标签',
        }

    def clean_name(self):
        name = self.cleaned_data['name']
        # 确保标签名不重复（不区分大小写）
        if Tag.objects.filter(name__iexact=name).exists():
            if self.instance and Tag.objects.filter(name__iexact=name).exclude(pk=self.instance.pk).exists():
                raise forms.ValidationError('该标签名已存在')
            elif not self.instance:
                raise forms.ValidationError('该标签名已存在')
        return name


class FoodItemForm(forms.ModelForm):
    class Meta:
        model = FoodItem
        fields = ['name', 'category', 'description', 'tags']

        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '例如：宫保鸡丁、番茄鸡蛋面'}),
            'category': forms.Select(attrs={'class': 'form-select'}),
            'tags': forms.SelectMultiple(attrs={'class': 'form-select'}),
            'description': forms.Textarea(attrs={'rows': 3, 'class': 'form-control', 'placeholder': '例如：这是一道经典的川菜，主要原料是鸡丁和花生米...'}),
        }
        labels = {
            'name': '食物名称',
            'category': '食物类别',
            'description': '食物描述',
            'tags': '标签',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 只保留“有父标签”的选项
        self.fields['tags'].queryset = Tag.objects.filter(parent__isnull=False)


class DailyFoodRecordForm(forms.ModelForm):
    class Meta:
        model = DailyFoodRecord
        fields = ['breakfast', 'lunch', 'dinner', 'snacks', 'notes', 'tags']
        widgets = {
            'breakfast': forms.Select(attrs={'class': 'form-select'}),
            'lunch': forms.Select(attrs={'class': 'form-select'}),
            'dinner': forms.Select(attrs={'class': 'form-select'}),
            'snacks': forms.SelectMultiple(attrs={'class': 'form-select'}),
            'tags': forms.SelectMultiple(attrs={'class': 'form-select'}),
            'notes': forms.Textarea(attrs={'rows': 3, 'placeholder': '记录今天的饮食感受...'}),
        }


class RecipeForm(forms.ModelForm):
    """做菜指南表单"""
    class Meta:
        model = Recipe
        fields = ['name', 'description', 'difficulty', 'cooking_time', 'servings', 'category', 'tags', 'image']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '例如：宫保鸡丁'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 4, 'placeholder': '简单描述这道菜的特点...'}),
            'difficulty': forms.Select(attrs={'class': 'form-select'}),
            'cooking_time': forms.Select(attrs={'class': 'form-select'}),
            'servings': forms.NumberInput(attrs={'class': 'form-control', 'min': 1, 'max': 20}),
            'category': forms.Select(attrs={'class': 'form-select'}),
            'tags': forms.SelectMultiple(attrs={'class': 'form-select'}),
            'image': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*'}),
        }
        labels = {
            'name': '菜品名称',
            'description': '菜品描述',
            'difficulty': '制作难度',
            'cooking_time': '制作时间',
            'servings': '份数',
            'category': '菜品分类',
            'tags': '相关标签',
            'image': '菜品图片',
        }


class RecipeIngredientForm(forms.ModelForm):
    """菜品食材表单"""
    class Meta:
        model = RecipeIngredient
        fields = ['name', 'amount', 'unit', 'notes', 'order']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '食材名称'}),
            'amount': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '用量，如：100'}),
            'unit': forms.Select(attrs={'class': 'form-select'}),
            'notes': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '备注（可选）'}),
            'order': forms.NumberInput(attrs={'class': 'form-control', 'min': 0}),
        }
        labels = {
            'name': '食材名称',
            'amount': '用量',
            'unit': '单位',
            'notes': '备注',
            'order': '排序',
        }


class RecipeStepForm(forms.ModelForm):
    """制作步骤表单"""
    class Meta:
        model = RecipeStep
        fields = ['step_number', 'title', 'description', 'cooking_time', 'heat_level', 'image', 'tips']
        widgets = {
            'step_number': forms.NumberInput(attrs={'class': 'form-control', 'min': 1}),
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '步骤标题'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 4, 'placeholder': '详细描述制作过程...'}),
            'cooking_time': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '例如：5分钟'}),
            'heat_level': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '例如：大火、中火、小火'}),
            'image': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*'}),
            'tips': forms.Textarea(attrs={'class': 'form-control', 'rows': 2, 'placeholder': '制作小贴士...'}),
        }
        labels = {
            'step_number': '步骤序号',
            'title': '步骤标题',
            'description': '步骤描述',
            'cooking_time': '此步骤用时',
            'heat_level': '火候',
            'image': '步骤图片',
            'tips': '小贴士',
        }


# 内联表单集
RecipeIngredientFormSet = forms.inlineformset_factory(
    Recipe, RecipeIngredient,
    form=RecipeIngredientForm,
    extra=3,  # 默认显示3个食材输入框
    can_delete=True,
    can_delete_extra=True,
)

RecipeStepFormSet = forms.inlineformset_factory(
    Recipe, RecipeStep,
    form=RecipeStepForm,
    extra=2,  # 默认显示2个步骤输入框
    can_delete=True,
    can_delete_extra=True,
)